<template>
  <div class="app-container">
    <px-form
      v-show="showSearch"
      ref="queryRef"
      :model="queryParams"
      :inline="true"
      label-width="90px"
      :rules="queryParams.dataFormat === 'actualConsumption' ? rules : null"
    >
      <px-form-item
        v-if="activeName === 'ELECTRICTITY'"
        label="查询方式"
        prop="queryType"
      >
        <px-select
          v-model="queryParams.queryType"
          placeholder="请选择查询方式"
          style="width: 240px"
          @change="changeQueryType"
        >
          <px-option
            v-for="item in query_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </px-select>
      </px-form-item>
      <px-form-item label="数据格式" prop="dataFormat">
        <px-select
          v-model="queryParams.dataFormat"
          placeholder="请选择数据格式"
          clearable
          style="width: 240px"
          @change="handleChange"
        >
          <px-option
            v-for="item in data_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </px-select>
      </px-form-item>
      <px-form-item label="时间" style="width: 480px">
        <px-date-picker
          v-if="queryParams.queryType === 'Month'"
          v-model="dateRange"
          value-format="YYYY-MM"
          type="monthrange"
          range-separator="-"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
        />
        <px-date-picker
          v-else
          v-model="dateRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </px-form-item>
      <px-form-item
        v-if="activeName === 'ELECTRICTITY'"
        label="电表/表号"
        prop="meterNo"
      >
        <px-input
          v-model="queryParams.meterNo"
          placeholder="请输入电表名称/表号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </px-form-item>
      <px-form-item>
        <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
        <px-button icon="" @click="resetQuery">重置</px-button>
      </px-form-item>
    </px-form>
    <px-row v-if="activeName !== 'ELECTRICTITY'" :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button type="primary" @click="handleExport">导出</px-button>
      </px-col>
    </px-row>
    <electricityTable
      v-if="activeName === 'ELECTRICTITY'"
      :loading="loading"
      :table-data="tableData"
      :query-params="queryParams"
    />
    <commonTable
      v-if="activeName !== 'ELECTRICTITY'"
      :loading="loading"
      :table-data="tableData"
      :query-params="queryParams"
      :active-name="activeName"
    />
    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :total="total"
      @pagination="getList"
    />
  </div>
</template>

<script setup lang="ts">
import {
  getCurrentInstance,
  ref,
  reactive,
  toRefs,
  computed,
  onMounted,
  onUnmounted
} from "vue";
import { energyReport, energyReportCommon } from "@/api/modules/energy";
import { emitter } from "@/utils/mitt";
import electricityTable from "./components/electricityTable.vue";
import commonTable from "./components/commonTable.vue";
import { useRouterStoreHook } from "@/store/modules/router";

const routerStore = useRouterStoreHook();
const activeName = ref("ELECTRICTITY"); // 默认电
const tableData = ref([]);
emitter.on("viceMenuChange", val => {
  activeName.value = val;
  getList();
});

onMounted(() => {
  getList();
});

onUnmounted(() => {
  emitter.off("viceMenuChange");
});
// 表单校验规则
const rules = computed(() => ({
  meterNo: [
    {
      required: true,
      message: "电表名称/表号不能为空",
      trigger: ["blur", "change"]
    }
  ]
}));
const { proxy }: any = getCurrentInstance();
const data_type = ref([
  {
    label: "读表数",
    value: "MeterReading"
  },
  {
    label: "按消耗",
    value: "actualConsumption"
  }
]);
const query_type = ref([
  {
    label: "按日期",
    value: "Date"
  },
  {
    label: "按月度",
    value: "Month"
  }
]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);

// 默认查询前1h数据
const dateRange = ref([
  proxy.parseTime(
    new Date().getTime() - 3600 * 1000 + 1000,
    "{y}-{m}-{d} {h}:{i}:{s}"
  ),
  proxy.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    meterNo: undefined,
    queryType: "Date",
    dataFormat: "MeterReading"
  }
});

const { queryParams } = toRefs(data);

/** 查询登录日志 */
function changeQueryType() {
  dateRange.value = [];
}

/**
 * 切换数据格式
 */
function handleChange() {
  queryParams.value.meterNo = "";
  proxy.$refs["queryRef"].clearValidate();
}

/** 查询登录日志 */
function getList() {
  const params = {
    className: routerStore.subject === "ALL" ? "" : routerStore.subject,
    energyType: activeName.value,
    ...queryParams.value
  };
  loading.value = true;
  if (activeName.value === "ELECTRICTITY") {
    energyReport(proxy.addDateRange(params, dateRange.value)).then(
      (response: any) => {
        tableData.value = response.dataList;
        total.value = response.total;
        loading.value = false;
      }
    );
  } else {
    energyReportCommon(proxy.addDateRange(params, dateRange.value)).then(
      (response: any) => {
        tableData.value = response.dataList || response.data;
        total.value = response.total;
        loading.value = false;
      }
    );
  }
}
/** 搜索按钮操作 */
function handleQuery() {
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    queryParams.value.pageNum = 1;
    getList();
  });
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [
    proxy.parseTime(
      new Date().getTime() - 3600 * 1000 + 1000,
      "{y}-{m}-{d} {h}:{i}:{s}"
    ),
    proxy.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
  ];
  handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
  const params = {
    className: routerStore.subject === "ALL" ? "" : routerStore.subject,
    energyType: activeName.value,
    ...queryParams.value
  };
  proxy.download(
    "post",
    "/energy/api/v1/report/exportEnergyReport",
    proxy.addDateRange(params, dateRange.value),
    `能效报表_${new Date().getTime()}`
  );
}
</script>

<style lang="scss" scoped>
.app-container {
  width: 100%;
  height: calc(100% - 97px);
  background-color: #fff;
}

.top_tabs {
  margin-top: 24px;
  margin-left: 20px;
}
</style>
